<template>
  <div class="search">
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <van-search
      v-model.trim="value"
      shape="round"
      show-action
      @input="onInput"
      placeholder="请输入搜索关键词"
      @search="onSearch(value)"
    >
      <template #action>
        <div @click="onSearch(value)">搜索</div>
      </template>
    </van-search>
    <!-- 推荐 -->
    <van-cell-group v-if="value">
      <van-cell
        v-for="item in searchList"
        :key="item"
        icon="search"
        @click="onSearch(item)"
      >
        <span v-html="highlight(item, value)"></span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell
        @click="onSearch(item)"
        v-for="(item, index) in historyList"
        :key="index"
        :title="item"
      >
        <van-icon @click.stop="delHistoryFn(item)" name="close" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSearch } from '@/api/search'
import { setHistoryList, getHistoryList } from '@/utils/storage'
export default {
  name: 'Search',
  data() {
    return {
      value: '',
      searchList: [],
      historyList: getHistoryList()
    }
  },
  methods: {
    // 高亮
    highlight(str, keyword) {
      const reg = new RegExp(keyword, 'gi')
      return str.replace(
        reg,
        (item) => `<span style="color:red">${item}</span>`
      )
    },
    // 搜索赋值
    onInput() {
      clearTimeout(this.timerId)

      this.timerId = setTimeout(async () => {
        if (this.value.length === 0) {
          this.searchList = []
          return
        }
        const res = await getSearch(this.value)
        console.log(res)

        if (res.data.options[0] === null) {
          return (this.searchList = [])
        }
        this.searchList = res.data.options
      }, 3000)
    },
    // 搜索提交
    onSearch(item) {
      if (!item) {
        return this.$toast('输入内容不能为空')
      }
      console.log('搜索中...')
      this.historyList.unshift(this.value)
      setHistoryList(this.historyList)
      console.log(item)
      this.$router.push({
        path: '/search/searcResult',
        query: {
          keyword: item
        }
      })
    },
    // 删除历史记录
    delHistoryFn(index) {
      this.historyList = this.historyList.filter((item) => item !== index)
    }
  }
}
</script>

<style></style>
